<?php
include 'config.php';
// 处理预检请求
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
    header("Access-Control-Allow-Headers: Content-Type");
    header("HTTP/1.1 200 OK");
    exit();
}


header("Content-Type: application/json");
// 检查是否为 POST 请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405); // Method Not Allowed
    echo json_encode(['error' => 'Only POST method is allowed']);
    exit;
}

// 获取 POST 数据
$data = json_decode(file_get_contents('php://input'), true);

// 验证数据
if (!isset($data['username']) || !isset($data['chatMessages'])) {
    http_response_code(400); // Bad Request
    echo json_encode(['error' => 'Invalid request data']);
    exit;
}

$username = $data['username'];
$chatMessages = $data['chatMessages'];

// 构造文件路径
$filePath = __DIR__ . "/data/{$username}.json";

// 读取现有数据（如果存在）
if (file_exists($filePath)) {
    $existingData = json_decode(file_get_contents($filePath), true);
} else {
    $existingData = [];
}

// 更新 chatMessages 字段
$existingData['chatMessages'] = $chatMessages;

// 保存到文件
file_put_contents($filePath, json_encode($existingData));

// 返回成功响应
echo json_encode(['status' => 'success']);
?>